local ConsoleWnd= class(zui.Window)
local debug = require "debug/debug"

function ConsoleWnd:ctor()
	self:createWindow("命令窗口",self.POS_CENTER,self.POS_CENTER,800,500)
end

function ConsoleWnd:updateValues(text)
	if #text==0 then
		local cmdValues={}
		for k,v in pairs(_G) do
			if type(v)=="function" then
				table.insert(cmdValues,k.."()")
			else
				table.insert(cmdValues,k)
			end
		end
		self._cmdValues = cmdValues
	else
		local cmdValues={}
		local path=""
		local map = _G
		local fields = string.split(text,'.')

		for i=1,#fields-1 do
			map = map[fields[i]]
			path = path..fields[i].."."
			if not map then
				break
			end
		end
		
		if string.sub(text,-1,-1)=='.' then
			map = map[fields[#fields]]
			path = path..fields[#fields].."."
			if map then
				for k,v in pairs(map) do
					if type(v)=="function" then
						table.insert(cmdValues,path..k.."()")
					else
						table.insert(cmdValues,path..k)
					end
				end				
			end
		else
			if map then
				local lastField = fields[#fields]
				--log("lastField "..lastField)
				for k,v in pairs(map) do
					if utils.strFind(k,lastField) then
						if type(v)=="function" then
							table.insert(cmdValues,path..k.."()")
						else
							table.insert(cmdValues,path..k)
						end
					end
				end
			else
				loge("not find path")
			end
		end
		
		self._cmdValues = cmdValues
	end
	
	--logDump(self._cmdValues)
end


function ConsoleWnd:onInit()
	self._dpiScale = self:getScale()
	self:loadLayout("layout/console_window.xml")
	self._cmdList = self:findControl("commendList")
	self._logEdit = self:findControl("logEdit")
	self._cmdValues={}
	self:updateValues("")
	
	self._cmdList:setDataSource({
		numberOfIndex=ConsoleWnd.getListCount,
		heightForIndex=ConsoleWnd.getItemHeight,
		cellAtIndex=ConsoleWnd.cellAtIndex,
	})
	
	self._cmdList:reload()

end


function ConsoleWnd:getListCount()
	--log("count："..#self._cmdValues)
	return #self._cmdValues
end

function ConsoleWnd:getItemHeight(idx)
	return self._dpiScale * 30
end

function ConsoleWnd:cellAtIndex(size,idx)
	local item = self._cmdList:getReusableCell(0)
	if not item then
		item = zui.ListCell.new()
		item:setReuseId(0)
		
		local label = zui.Label.new()
		label:setText(self._cmdValues[idx+1])
		label:setTextStyle(label.DT_VCENTER)
		label:setTextPadding({left=3})
		item:add(label)
	else
		item:getItemAt(0):setText(self._cmdValues[idx+1])
	end
	return item
end

function ConsoleWnd:onTextChanged(edit)
	local text = edit:getText()
	self:updateValues(text)
	self._cmdList:reload()
end

--选择了item
function ConsoleWnd:selectCmd(list,idx)
	local text = self._cmdValues[idx+1]
	if text then
		self:findControl("cmdEdit"):setText(text)
	end
end

function ConsoleWnd:execCmd(edit)
	local text = edit:getText()
	
	local func,err = loadstring("return "..text)
	if type(func) =="function" then
		local rs,data=pcall(func)
		self:logn(tostring(data))
	else
		self:logn(err)
	end
end

function ConsoleWnd:onUpDown(edit,bup)
	if bup then
		self._cmdList:selectPrevious()
	else
		self._cmdList:selectNext()
	end
end

function ConsoleWnd:runCmd(btn)
	local edit=self:findControl("cmdEdit")
	self:execCmd(edit)
end

function ConsoleWnd:clearCmd(edit)
	edit:setText("")
	self:updateValues("")
	self._cmdList:reload()
end


function ConsoleWnd:close()
	--self:destroy()
	consoleWnd=nil
	
	zui.Application.instance():quit()
end

function ConsoleWnd:log(text)
	if self._logEdit:getLineCount()>1000 then
		self._logEdit:setText(text)
	else
		self._logEdit:appendText(text)
	end
	self._logEdit:endDown()
end

function ConsoleWnd:logn(text)
	if self._logEdit:getLineCount()>1000 then
		self._logEdit:setText(text.."\n")
	else
		self._logEdit:appendText(text.."\n")
	end
	self._logEdit:endDown()
end

function ConsoleWnd:onDropFile(file)
	self:logn("Exec:"..file)
	local data = zui.FileUtils.instance():getFileData(file)
	local func = loadstring(data,file)
	local rslt,err = pcall(func)
	if not rslt then
		self:logn(err)
	end
end

function ConsoleWnd:onCommandClose()
	zui.Application.instance():quit()
end

consoleWnd = ConsoleWnd.new()

--接管打印函数
if not debug.isDebug() then
	function print(...)
		local args={...}
		local data = table.concat(args,"  ")
		consoleWnd:logn(data)
	end
end

